package com.hdcx.Minfresh.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hdcx.Minfresh.R;
import com.hdcx.Minfresh.base.ZjbBaseActivity;
import com.hdcx.Minfresh.model.DiYongQuan;
import com.hdcx.Minfresh.model.Statue;
import com.hdcx.Minfresh.refreshview.CustomerFooter;
import com.hdcx.Minfresh.refreshview.XRefreshView;
import com.hdcx.Minfresh.url.MyUrl;
import com.hdcx.Minfresh.util.AppUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class PointChangeReActivity extends ZjbBaseActivity implements View.OnClickListener {
    private XRefreshView mXRefreshView;
    private ListView mListViewXiaoFeiJiLu;
    private MyAdapter mAdapter;
    int num = 1;
    int totleNum;
    private List<DiYongQuan.ListEntity> mListEntityList = new ArrayList<>();
    private int mUserscore;
    private TextView mTv_right;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_point_change_re);
        init();
    }

    @Override
    protected void initIntent() {

    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void findID() {
        mXRefreshView = (XRefreshView) findViewById(R.id.xRefreshView);
        mListViewXiaoFeiJiLu = (ListView) findViewById(R.id.listView);
        mTv_right = (TextView) findViewById(R.id.tv_right);
    }

    @Override
    protected void initViews() {
        ((TextView) findViewById(R.id.tv_title)).setText("积分兑换");
        mAdapter = new MyAdapter();
        mListViewXiaoFeiJiLu.setAdapter(mAdapter);
        initXRefreshView();
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.tv_left).setOnClickListener(this);
    }

    @Override
    protected void initData() {
        showLoading();
        JSONObject json = new JSONObject();
        try {
            json.put("page", num);
            json.put("uid", AppUtil.getUserId());
            json.put("size", "10");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.postString()
                .url(MyUrl.ULIST)
                .content(json.toString())
                .build()
                .execute(new Callback<DiYongQuan>() {
                    @Override
                    public DiYongQuan parseNetworkResponse(Response response) throws IOException {
                        String json = response.body().string();
                        Log.e("PointChangeActivity", "PointChangeActivity--parseNetworkResponse--兑换卷" + json);
                        return new Gson().fromJson(json, DiYongQuan.class);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        AppUtil.closeLoading();
                    }

                    @Override
                    public void onResponse(DiYongQuan response) {
                        closeLoading();
                        if (response.getStatus() == 1) {
                            num++;
                            totleNum = response.getCount();
                            mTv_right.setText("积分："+response.getUserscore());
                            mUserscore = response.getUserscore();
                            mListEntityList.addAll(response.getList());
                            mAdapter.notifyDataSetChanged();
                            mXRefreshView.stopLoadMore();
                            mXRefreshView.stopRefresh();
                        }
                    }
                });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_left:
                finish();
                break;
        }
    }

    private void initXRefreshView() {
        mXRefreshView.setPullLoadEnable(true);
        mXRefreshView.setPinnedTime(1000);
        mXRefreshView.setMoveForHorizontal(true);
        mXRefreshView.setAutoLoadMore(false);
        mXRefreshView.setCustomFooterView(new CustomerFooter(PointChangeReActivity.this));
        mXRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                num = 1;
                mListEntityList.clear();
                initData();
            }

            @Override
            public void onLoadMore(boolean isSlience) {
                if (num > totleNum) {
                    Toast.makeText(PointChangeReActivity.this, "没有更多了", Toast.LENGTH_SHORT).show();
                    mXRefreshView.stopLoadMore();
                } else {
                    initData();
                }
            }
        });
    }

    class MyAdapter extends BaseAdapter {
        class ViewHolder {
            public TextView tv_img_diyongquan;
            public TextView textViewHowMuch;
            public TextView textViewLimit;
            public TextView textViewCanUse;
            public TextView textViewScroe;
            public Button buttonToDo;
        }

        @Override
        public int getCount() {
            return mListEntityList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.item_diyongquan, null);
                holder.tv_img_diyongquan = (TextView) convertView.findViewById(R.id.tv_img_diyongquan);
                holder.textViewHowMuch = (TextView) convertView.findViewById(R.id.textViewHowMuch);
                holder.textViewLimit = (TextView) convertView.findViewById(R.id.textViewLimit);
                holder.textViewCanUse = (TextView) convertView.findViewById(R.id.textViewCanUse);
                holder.textViewScroe = (TextView) convertView.findViewById(R.id.textViewScroe);
                holder.buttonToDo = (Button) convertView.findViewById(R.id.buttonToDo);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final DiYongQuan.ListEntity listEntity = mListEntityList.get(position);
            if (listEntity.getColor() == 1) {
                holder.tv_img_diyongquan.setBackgroundResource(R.mipmap.duihuanquan01);
            } else if (listEntity.getColor() == 2) {
                holder.tv_img_diyongquan.setBackgroundResource(R.mipmap.duihuanquan02);
            } else if (listEntity.getColor() == 3) {
                holder.tv_img_diyongquan.setBackgroundResource(R.mipmap.duihuanquan03);
            } else if (listEntity.getColor() == 4) {
                holder.tv_img_diyongquan.setBackgroundResource(R.mipmap.duihuanquan04);
            }
            holder.tv_img_diyongquan.setText(listEntity.getBonus_value());
            holder.textViewHowMuch.setText(listEntity.getBonus_name());
            holder.textViewLimit.setText("· 满" + listEntity.getMin_amount() + "元可用");
            holder.textViewCanUse.setText("· 有效期" + listEntity.getTime() + "天");
            holder.textViewScroe.setText(listEntity.getScore() + "分");
            if (mUserscore >=Integer.parseInt(listEntity.getScore())) {
                holder.buttonToDo.setEnabled(true);
            } else {
                holder.buttonToDo.setEnabled(false);
            }
            holder.buttonToDo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new AlertDialog.Builder(PointChangeReActivity.this)
                            .setTitle("提示")
                            .setMessage("确认要兑换吗？")
                            .setPositiveButton("是", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    duiHuan(Integer.parseInt(listEntity.getId()));
                                }
                            })
                            .setNegativeButton("否",null)
                            .create()
                            .show();
                }
            });
            return convertView;
        }
    }

    private void duiHuan(int id) {
        JSONObject json = new JSONObject();
        try {
            json.put("uid", AppUtil.getUserId());
            json.put("id", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.postString()
                .url(MyUrl.USER_EXCHANGE)
                .content(json.toString())
                .build()
                .execute(new Callback<Statue>() {
                    @Override
                    public Statue parseNetworkResponse(Response response) throws IOException {
                        String json = response.body().string();
                        Log.e("PointChangeActivity", "PointChangeActivity--parseNetworkResponse--兑换抵用券" + json);
                        return new Gson().fromJson(json, Statue.class);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        AppUtil.closeLoading();
                    }

                    @Override
                    public void onResponse(Statue response) {
                        closeLoading();
                        if (response.getStatus() == 1) {

                        }else {

                        }
                        num = 1;
                        mListEntityList.clear();
                        initData();
                        Toast.makeText(PointChangeReActivity.this, response.getInfo(), Toast.LENGTH_SHORT).show();
                    }
                });
    }
}
